<template>
	<view class="header">
		<view class="left">
			<view class="logo">
				<image :src="ICON_LOGO" mode="widthFix" />
			</view>
			<view :class="['menu', { hide: hideMenu }]">
				<view :class="['item', {active: active === '首页'}]"
					@click="active !== '首页' && goto('/pages/home/index')">
					首页</view>
				<view :class="['item', {active: active === '主菜单'}]"
					@click="active !== '主菜单' && goto('/pages/workbench/index')">主菜单</view>
				<view :class="['item', {active: active === '系统设置'}]"
					@click="active !== '系统设置' && goto('/pages/settings/index')">系统设置</view>
			</view>
		</view>
		<view class="info">
			<view class="scanCode" @click="scanCode" v-if="this.$listeners.scanCode">
				<view class="icon">
					<u-icon name="scan" color="#fff" size="28"></u-icon>
				</view>
				<view class="text">
					扫一扫
				</view>
			</view>
			<view class="device notice" @click="goto('/pages/andon/index')">
				<image :src="emailIcon" />
				<view class="total" v-show="noticeTotal!=0">
					{{noticeTotal>99?99:noticeTotal}}
				</view>
			</view>
			<view class="device" @click="goto('/pages/device/index')">
				<image :src="icon" />
				<view class="name text-overflow-ellipsis">
					{{ device.deviceNo }}
				</view>
			</view>
			<view class="datetime">
				<view class="time">
					{{ timeStr }}
				</view>
				<view class="date">
					<view class="week">
						{{ weekStr() }}
					</view>
					<view class="day">
						{{ dayjs().format('YYYY/MM/DD') }}
					</view>
				</view>
			</view>
			<view class="profile" @click="device && goto('/pages/settings/index')">
				<image :src="avatar" class="avatar" />
				<view class="nikename">{{ userInfo.realname }}</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getUserInfo,
		getDevice,
	} from "@/store/user.js";
	import icon from './img/machine.png';
	import emailIcon from './img/email.png';
	import avatar from './img/avatar.jpg';
	import fetch from "@/utils/fetch";
	import {
		dayjs
	} from '@/uni_modules/iRainna-dayjs/js_sdk/dayjs.min.js'
	import ICON_LOGO from './img/ME.png';

	export default {
		name: "MyTopbar",
		props: {
			active: String,
			hideMenu: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				ICON_LOGO,
				userInfo: getUserInfo(),
				device: getDevice(),
				icon,
				emailIcon,
				avatar,
				timeStr: dayjs().format('HH:mm'),
				noticeTotal: 0,
				myInterval: null,
			};
		},
		methods: {
			// scanCode() {
			// 	const that = this;
			// 	const mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module")
			// 	mpaasScanModule.mpaasScan({
			// 			// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
			// 			'scanType': ['qrCode', 'barCode'],
			// 			// 是否隐藏相册，默认false不隐藏
			// 			'hideAlbum': false
			// 		},
			// 		(ret) => {
			// 			console.log(JSON.stringify(ret))
			// 			if (ret.resp_code == 1000) {
			// 				that.$emit('scanCode', ret.resp_result);
			// 			}
			// 			// uni.showModal({
			// 			// 	title: "弹窗标题",
			// 			// 	// 返回值中，resp_code 表示返回结果值，10：用户取消，11：其他错误，1000：成功
			// 			// 	// 返回值中，resp_message 表示返回结果信息
			// 			// 	// 返回值中，resp_result 表示扫码结果，只有成功才会有返回
			// 			// 	content: JSON.stringify(ret),
			// 			// 	showCancel: false,
			// 			// 	confirmText: "确定"
			// 			// })
			// 		})
			// 	// uni.scanCode({
			// 	//     success(res) {
			// 	//         that.$emit('scanCode', res.result);
			// 	//     },
			// 	// });
			// },
			scanCode() {
				const that = this;
				uni.scanCode({
					// 扫码类型设置（与mPaaS参数一致）
					scanType: ['qrCode', 'barCode'],
					// 是否只允许相机扫码（对应hideAlbum功能）
					onlyFromCamera: false, // false表示允许从相册选择
					success: (res) => {
						console.log('扫码结果:', res);
						// 模拟mPaaS的成功状态码1000
						that.$emit('scanCode', res.result);
					},
					fail: (err) => {
						console.error('扫码失败:', err);
						// 模拟mPaaS的错误状态码（用户取消/其他错误）
						const ret = {
							resp_code: err.errMsg.includes('cancel') ? 10 : 11,
							resp_message: err.errMsg
						};
						console.log(JSON.stringify(ret));
						// 如需保留原错误弹窗逻辑，取消下方注释
						/* uni.showModal({
						  title: "扫码失败",
						  content: err.errMsg,
						  showCancel: false
						}); */
					}
				});
			},
			updateDeviceInfo() {
				this.device = getDevice()
			},
			getNoticeTotal() {
				fetch('get', '/dms/messageWarning/queryTotalUnread').then((res) => {
					this.noticeTotal = res;
				});
			},
			weekStr() {
				const week = dayjs().day();
				switch (week) {
					case 0:
						return '星期日';
					case 1:
						return '星期一';
					case 2:
						return '星期二';
					case 3:
						return '星期三';
					case 4:
						return '星期四';
					case 5:
						return '星期五';
					case 6:
						return '星期六';
				}
			},
			goto(url) {
				uni.redirectTo({
					url: url,
					animationType: "pop-in",
					animationDuration: 1000,
				});
			}
		},
		mounted: function() {
			setInterval(() => {
				this.timeStr = dayjs().format('HH:mm');
			}, 1000);
			this.getNoticeTotal();
			// this.myInterval=setInterval(() => {
			// 	this.getNoticeTotal();
			// }, 5000);
		},
		// destroyed() {
		// 	clearInterval(this.myInterval)
		// }
	}
</script>

<style scoped lang="scss">
	.header {
		position: relative;
		display: flex;
		justify-content: space-between;
		padding: 3.9rem 5rem;
		z-index: 1;

		.left {
			display: flex;

			.logo {
				display: flex;
				justify-content: center;
				align-items: center;
				color: #fff;
				width: 22rem;

				uni-image,
				img {
					width: 100%;
				}
			}
		}

		.menu {
			display: flex;
			margin-left: 6rem;

			.item {
				color: #d2e6f1;
				background: #2f6da0;
				padding: 2rem 6rem;
				border-radius: 1rem;

				&.active {
					color: #fff;
					background: #447caa;
					font-weight: bold;
				}
			}

			&.hide {
				display: none;
			}
		}

		.info {
			display: flex;
			justify-content: center;
			align-items: center;
			color: #d2e6f1;

			.scanCode {
				display: flex;
				align-items: center;
				margin-right: 3rem;

				.icon {
					height: 6rem;
					width: 6rem;
					background-color: #477eab;
					border-radius: 5rem;
					display: flex;
					justify-content: center;
					align-items: center;
					margin-right: 1rem;

					/deep/ .u-icon__icon {
						font-size: 4rem !important;
					}
				}

			}

			.device {
				display: flex;
				justify-content: center;
				align-items: center;
				position: relative;

				image {
					width: 3rem;
					height: 3rem;
					padding: 1.5rem;
					box-sizing: content-box;
					border-radius: 10rem;
					background: #477eab;
					margin-right: 2rem;
				}

				.total {
					position: absolute;
					background-color: red;
					color: white;
					border-radius: 50%;
					// display: flex;
					line-height: 2.5rem;
					font-size: 1.5rem;
					text-align: center;
					align-items: center;
					justify-content: center;
					top: 5%;
					right: 17%;
					width: 2.5rem;
					height: 2.5rem;
				}
			}

			.datetime {
				display: flex;
				align-items: center;
				border-left: 1px solid #6696bb;
				border-right: 1px solid #6696bb;
				padding: 0 3rem;
				margin: 0 3rem;

				.time {
					display: flex;
					flex-direction: column;
					align-items: center;
					font-size: 5rem;
					margin-right: 3rem;
				}

				.date {
					display: flex;
					flex-direction: column;
					align-items: center;

					.week {}

					.day {}
				}

			}
		}

		.profile {
			display: flex;
			align-items: center;

			.avatar {
				width: 5rem;
				height: 5rem;
				padding: 0.5rem;
				box-sizing: content-box;
				border-radius: 10rem;
				background: #efedff;
				margin-right: 1rem;

				/deep/ div {
					border-radius: 10rem;
				}
			}

			.nikename {
				margin-left: 1rem;
			}

			.menu {
				display: none;

				.item {}
			}
		}
	}

	.text-overflow-ellipsis {
		max-width: 15rem;
		padding: 0;
		text-overflow: ellipsis;
		overflow: hidden;
		white-space: nowrap;
		margin: 0 auto;
	}
</style>